package com.yds.bluetooth.utils

/**
 * 作者:     YDS
 * 创建时间: 2023/8/7 9:29
 * 页面描述: 16进制转换帮助类
 */
object YDSHexHelper {

    /**
     * 将16进制字符串转换为字节数组
     *
     * @param hex 16进制字符串
     * @return 字节数组
     */
    fun hexToBytes(hex: String?): ByteArray {
        if (hex == null || hex.isEmpty()) {
            return ByteArray(0)
        }
        var hexStr = hex
        if (hexStr.contains(" "))
            hexStr = hex.replace(" ", "")
        val len = hexStr.length
        val data = ByteArray(len / 2)
        var i = 0
        while (i < len) {
            data[i / 2] = ((Character.digit(hexStr[i], 16) shl 4)
                    + Character.digit(hexStr[i + 1], 16)).toByte()
            i += 2
        }
        return data
    }

    /**
     * 将字节数组转换为16进制字符串
     *
     * @param bytes 字节数组
     * @return 16进制字符串
     */
    fun bytesToHex(bytes: ByteArray?): String {
        if (bytes == null || bytes.isEmpty()) {
            return ""
        }
        val result = StringBuilder()
        var hex: String
        for (element in bytes) {
            hex = Integer.toHexString(element.toInt() and 0xFF)
            if (hex.length == 1) {
                hex = "0$hex"
            }
            result.append(hex.toUpperCase()).append(" ")
        }
        return result.toString()
    }

}